import axios from "axios";
export default {
  namespaced: true,
  state: {
    cartList: [],
  },
  mutations: {
    UpdateCartList(state, payload) {
      state.cartList = payload;
      console.log(state.cartList);
    },

    UpdateCount(state, payload) {
      let item = state.cartList.find((item) => item.id === payload.id);
      item.count = payload.count;
      console.log(state.cartList);
    },
  },
  actions: {
    async GetCartList(context) {
      const res = await axios.get("http://localhost:3000/cart");
      context.commit("UpdateCartList", res.data);
    },
    async UpdateCountAsync(context, obj) {
      const res = await axios.patch("http://localhost:3000/cart/" + obj.id, {
        count: obj.count,
      });
      //需要判断提交是否成功
      context.commit("UpdateCount", obj);
    },
  },
  getters: {
    totalCount(state) {
      let count = 0;
      state.cartList.forEach((item) => {
        count += item.count;
      });
      return count;
    },
    totalPrice(state) {
      let price = 0;
      state.cartList.forEach((item) => {
        price += item.count * item.price;
      });
      return price.toFixed(2);
    },
  },
};
